package com.chenjun.web.controller.oa;

import java.lang.reflect.InvocationTargetException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chenjun.common.base.ResultDto;
import com.chenjun.common.bean.Pagination;
import com.chenjun.common.model.DataGridModel;
import com.chenjun.common.model.DataGridSortModel;
import com.chenjun.core.dao.generator.entity.OaBillOvertimeApplication;
import com.chenjun.core.dao.generator.entity.SysUser;
import com.chenjun.core.service.oa.OvertimeManagerService;
import com.chenjun.core.vo.activiti.OvertimeDto;
import com.chenjun.web.controller.BaseController;

@SuppressWarnings("serial")
@RequestMapping("/overtime")
@Controller
public class OvertimeManagerController extends BaseController {
	
	@Resource
	private OvertimeManagerService overTimeManagerService;
	
	@Resource
	private RuntimeService runtimeService;
	
	@Resource
	private TaskService taskService;

	/**
	 * 页面展示
	 * @return
	 * ModelAndView
	 */
	@RequestMapping("/list.html")
	public ModelAndView index() {
		ModelAndView mv = new ModelAndView("activiti/overtime/list");
		return mv;
	}
	
	/**
	 * 分页搜索
	 * @param datagrid
	 * @return
	 * ResultDto
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@RequestMapping(value = "/search")
	@ResponseBody
	public ResultDto list(DataGridModel datagrid) {
		ResultDto rtDto = new ResultDto();
		datagrid.getSortBy().add(new DataGridSortModel("bill_date", DataGridSortModel.DESC));
		datagrid.getParams().put("emplId", getLoginUserId());
		Pagination data = overTimeManagerService.doPagination(datagrid);
		rtDto.setData(data);
		return rtDto;
	}

	/**
	 * 编辑页面元素
	 * @return
	 * ResultDto
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public ResultDto edit(@Valid OvertimeDto dto,Errors errors)  throws IllegalAccessException, InvocationTargetException{
		ResultDto rtDto = new ResultDto();
		
		//验证
		if (!hanleErrors(rtDto, errors)) { return rtDto; }
		SysUser loginUser = getLoginUser();
		OaBillOvertimeApplication  overtime = OvertimeDto.getModelByDto(dto);
		Calendar date = Calendar.getInstance();
		overtime.setNo(DateFormatUtils.format(date, "yyyyMMddHHmmss"));
		overtime.setBillDate(date.getTime());
		overtime.setStatus(10);
		overtime.setEmplId(loginUser.getId());
		overtime.setEmplCode(loginUser.getUserName());
		overtime.setEmplName(loginUser.getRealName());
		overtime.setYear(date.get(Calendar.YEAR));
		overtime.setMonth(date.get(Calendar.MONTH) + 1);
		int i = overTimeManagerService.createOrUpdate(overtime);
		if(i<=0){
			rtDto.resultError();
			rtDto.setMessage("编辑系统异常");
		}
		return rtDto;
	}

	/**
	 * 删除指定的记录
	 * @param id
	 * @return
	 * ResultDto
	 */
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public ResultDto delete(@PathVariable Integer id) {
		ResultDto rtDto = new ResultDto();
		OaBillOvertimeApplication overTime = overTimeManagerService.get(id);
		int result = 0;
		if (overTime != null) {
			result = overTimeManagerService.delete(id);
		}
		if (result <= 0) {
			rtDto.resultError();
			rtDto.setMessage("要删除的记录不存在!");
		}
		return rtDto;
	}

	/**
	 * 根据参数获取信息
	 * @param id
	 * @return
	 * ResultDto
	 */
	@RequestMapping("/get/{id}")
	@ResponseBody
	public ResultDto get(@PathVariable Integer id) {
		ResultDto rtDto = new ResultDto();
		rtDto.setData(overTimeManagerService.get(id));
		return rtDto;
	}
	
	/**
	 * 提交申请
	 */
	@RequestMapping("/apply/{id}")
	@ResponseBody
	public ResultDto submitLeaveApply(@PathVariable Integer id, @RequestParam("leaderships[]") List<String> leaderships){
		ResultDto rtDto = new ResultDto();
		if(leaderships.size() == 0){
			rtDto.resultWaring();
			rtDto.setMessage("请选择审批人");
			return rtDto;
		}
		OaBillOvertimeApplication overTime = overTimeManagerService.get(id);
		SysUser loginUser = getLoginUser();
		Map<String,Object> variables=new HashMap<String,Object>();
		variables.put("billID", id);
		// 设置用户id,用于流程记录发起人
		Authentication.setAuthenticatedUserId(loginUser.getId()); 
		// 启动流程
		ProcessInstance pi = runtimeService.startProcessInstanceByKey("overtime", variables);
		// 根据流程实例Id查询任务
		Task task=taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult(); 
		// 指定处理人
		taskService.setVariable(task.getId(), "leaderships", leaderships);
		// 提交请假单任务
		taskService.complete(task.getId());
		overTime.setStatus(20);
		overTime.setProcessInstanceId(pi.getProcessInstanceId());
		overTimeManagerService.createOrUpdate(overTime);
		return rtDto;
	}
	
}
